<template>
  <div class="song-audio">
    <audio ref="player" :src="url" controls="controls"
           @canplay="startPlay" @ended="end" preload="true" @timeupdate="timeupdate"
    >

    </audio>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex';

  export default {
    name: "SongAudio",
    computed:{
      ...mapGetters([
        'id',
        'url',
        'isPlay',           //播放状态
        'listOfSongs',     //当前歌曲列表
        'curTime',         //当前音乐的播放位置
        'changeTime',      //指定播放时刻
        'autoNext',        //用于自动触发播放下一首
        'volume'           //音量
      ])
    },
    watch:{
      isPlay:function() {
        this.togglePlay()
      },
      //跳转到指定播放时刻
      changeTime(){
        this.$refs.player.currentTime = this.changeTime;
      },
      //改变音量
      volume(val){
        this.$refs.player.volume = val;
      }
    },
    methods:{
      startPlay(){
        let player = this.$refs.player;
      //获取链接后准备播放
        this.$store.commit('setDuration',player.duration);
        //开始播放
        player.play();
        this.$store.commit('setIsPlay',true);
      },
      end(){
        this.$store.commit('setIsPlay',false);
        this.$store.commit('setCurTime',0);
        this.$store.commit('setAutoNext',!this.autoNext);
      },
    //  开始，暂停
      togglePlay(){
        let player = this.$refs.player;
        if(this.isPlay){
          player.play();
        }else{
          player.pause();
        }
      },
      //音乐播放时记录音乐的播放位置
      timeupdate(){
        this.$store.commit('setCurTime',this.$refs.player.currentTime);
      }
    }
  }
</script>

<style scoped>
  .song-audio{
    display: none;
  }
</style>
